import json
# import os
# import random

# from PIL import ImageDraw, Image, ImageFont
from django.contrib.auth import authenticate, login, logout
# from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.models import User
from django.shortcuts import render

# Create your views here.
from usermanage.models import UserInfo, Follow


class CustomBackend(ModelBackend):
    """邮箱也能登录"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserInfo.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class Users:
    # 注册
    @staticmethod
    def user_register(request):
        # data = json.loads(request.POST)
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')
        identity = data.get('identity')
        resetq = data.get('rstq')
        reseta = data.get('rsta')
        user = User.objects.filter(username=username).first()
        if username is None or password is None or email is None:
            return JsonResponse({'status': 2, 'message': '用户名或密码或邮箱为空'})
        if user is not None:
            return JsonResponse({'status': 5, 'message': '用户已存在'})
        user = User.objects.create_user(username=username, password=password, email=email)
        user.save()
        userinfo = UserInfo.objects.create(user=user, identity=identity, resetQuestion=resetq,
                                           resetAnswer=reseta)
        # userinfo = UserInfo.objects.get(user=user)
        # userinfo.identity = identity
        userinfo.save()
        return JsonResponse({
            "status": 0,
            "data": {
                "id": user.pk,
                "username": user.username,
            }
        })

    # 登录
    @staticmethod
    def user_login(request):
        if request.method == "POST":
            data = json.loads(request.body)
            username = data.get("username")
            password = data.get("password")
            if username is not None and password is not None:
                login_status = authenticate(request, username=username, password=password)
                if login_status is not None:
                    user_id = login_status.id
                    login(request, login_status)
                    return JsonResponse({
                        "status": 0,
                        "message": "登陆成功",
                        "current_user": user_id,
                    })
                else:
                    return JsonResponse({
                        "status": 6,
                        "message": "登录失败, 请检查用户名或者密码是否输入正确."
                    })
            else:
                return JsonResponse({
                    "status": 3,
                    "message": "参数错误"
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "error method"
            })

    # 注销
    @staticmethod
    def user_logout(request):
        logout(request)
        return JsonResponse({
            "status": 0,
            "message": "登出成功",
        })

    # 获取用户的关注列表
    @staticmethod
    def get_follows(request):
        if request.method == "POST":
            follower = json.loads(request.body).get("follower")
            if request.user.is_authenticated:
                follower = request.user.id
            try:
                follows = Follow.objects.filter(follower=follower)
            except Exception as e:
                return JsonResponse({
                    "status": 3,
                    "message": "该用户不存在",
                })
            else:
                follow_list = []
                for follow in follows:
                    follow_dic = {}
                    follow_dic['userid'] = follow.followed_id
                    # followed_dic['avaurl'] = followed.avatar
                    user = UserInfo.objects.get(id=follow.followed_id)
                    follow_dic['email'] = user.user.email
                    follow_dic['username'] = follow.followed.username
                    follow_list.append(follow_dic)
                return JsonResponse({
                    "status": 0,
                    "follow_list": follow_list,
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请求有误"
            })

    # 获取当前用户对目标用户的关注状态
    @staticmethod
    def get_follow_state(request):
        if request.method == "POST":
            data = json.loads(request.body)
            follower_id = data.get("follower")
            followed_id = data.get('followed')
            if request.user.is_authenticated:
                follower_id = request.user.id
            try:
                follow = Follow.objects.get(follower_id=follower_id, followed_id=followed_id)
            except Exception as e:
                return JsonResponse({
                    "status": 0,
                    "is_follow": False
                })
            else:
                return JsonResponse({
                    "status": 0,
                    "is_follow": True
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请求方式有误"
            })

    @staticmethod
    def resetpassword(request):
        if request.method == "POST":
            data = json.loads(request.body)
            username = data.get("username")
            rstans = data.get("rsta")
            newpassword = data.get("newpass")
            user = User.objects.get(username=username)
            curUser = UserInfo.objects.get(user=user)
            if curUser is None:
                return JsonResponse({"status": 3, "message": "curUser not exist"})
            if curUser.resetAnswer == rstans:
                user.set_password(newpassword)
                user.save()
                curUser.save()
                return JsonResponse({
                    "status": 0,
                    "message": "密码修改成功，请使用新密码登录"
                })
            else:
                return JsonResponse({
                    "status": 2,
                    "message": "密保问题答案错误"
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请求方式有误"
            })

    @staticmethod
    def get_resetquestion(request):
        if request.method == "POST":
            data = json.loads(request.body)
            username = data.get("username")
            user = UserInfo.objects.get(user__username=username)
            if user is None:
                return JsonResponse({"status": 3, "message": "user not exist"})
            return JsonResponse({
                "status": 0,
                "rstq": user.resetQuestion
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请求方式有误"
            })

    # 修改密码
    @staticmethod
    def modifypassword(request):
        if request.method == "POST":
            data = json.loads(request.body)
            oldpassword = data.get("oldpass")
            newpassword = data.get("newpass")
            if request.user is not None:
                user = request.user
                username = user.username
            else:
                username = data.get("username")
                user = UserInfo.objects.get(username=username)
            if user is None:
                return JsonResponse({"status": 3, "message": "用户不存在"})
            if oldpassword is not None and newpassword is not None and type is not None:
                islogin = authenticate(request, username=username, password=oldpassword)
                if islogin is None:
                    return JsonResponse({
                        "status": 2,
                        "message": "原密码错误"
                    })
                user.set_password(newpassword)
                user.save()
                return JsonResponse({
                    "status": 0,
                    "message": "修改成功"
                })
            else:
                return JsonResponse({
                    "status": 2,
                    "message": "参数错误"
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请求方式有误"
            })

    @staticmethod
    def follow(request):
        if request.method == "POST":
            data = json.loads(request.body)
            followed_id = data.get("followedid")
            follower_id = request.user.id
            try:
                follow = Follow.objects.get(follower_id=follower_id, followed_id=followed_id)
            except Exception as e:
                try:
                    follow = Follow.objects.create(follower_id=follower_id, followed_id=followed_id)
                except Exception as e:
                    return JsonResponse({
                        "status": 3,
                        "message": "此用户不存在"
                    })
                else:
                    follow.save()
                    return JsonResponse({
                        "status": 0,
                        "message": "关注成功"
                    })
            else:
                follow.delete()
                return JsonResponse({
                    "status": 0,
                    "message": "取消关注成功"
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请求方式有误"
            })

    @staticmethod
    def get_followeds(request):
        if request.method == "POST":
            followed_id = json.loads(request.body).get("followed")
            if request.user.is_authenticated:
                followed_id = request.user.id
            try:
                followeds = Follow.objects.filter(followed_id=followed_id)
            except Exception as e:
                return JsonResponse({
                    "status": 3,
                    "message": "该用户不存在"
                })
            else:
                followeds_list = []
                for followed in followeds:
                    followed_dic = {}
                    userid = followed.followed_id
                    followed_dic['userid'] = userid
                    user = UserInfo.objects.get(id=userid)
                    followed_dic['email'] = user.user.email
                    followed_dic['username'] = user.user.username
                    followeds_list.append(followed_dic)
                return JsonResponse({
                    "status": 0,
                    "followed_list": followeds_list
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请求方式有误"
            })

    @staticmethod
    def switchadmin(request):
        if request.method == 'POST':
            data = json.loads(request.body)
            id = data.get('id')
            if UserInfo.objects.filter(user_id=id).exists():
                user = UserInfo.objects.get(user_id=id)
                is_admin = user.isAdmin
                user.isAdmin = not is_admin
                is_admin = user.isAdmin
                user.save()
                return JsonResponse({
                    "status": 0,
                    "new_is_admin": is_admin
                })
            else:
                return JsonResponse({
                    "status": 3,
                    "message": "用户不存在"
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请求方式有误"
            })

    @staticmethod
    def switch_ban_status(request):
        data = json.loads(request.body)
        if request.user.is_authenticated:
            operator = request.user
            if not UserInfo.objects.get(user=operator).isAdmin:
                return JsonResponse({
                    "status": 4,
                    "message": "权限不足，不能执行封禁操作"
                })
        else:
            return JsonResponse({
                "status": 6,
                "message": "未登录，不能执行封禁操作"
            })
        user_id = data.get("id")
        username = data.get("username")
        if User.objects.filter(id=user_id).first() is None and User.objects.filter(username=username).first() is None:
            return JsonResponse({
                "status": 3,
                "message": "用户不存在"
            })
        if not User.objects.filter(id=user_id).first() is None:
            user = User.objects.get(id=user_id)
        if not User.objects.filter(username=username).first() is None:
            user = User.objects.get(username=username)
        # username = data.get("username")
        # if User.objects.filter(username=username).first() is None:
        #     return JsonResponse({
        #         "status": 2,
        #         "message": "用户不存在"
        #     })
        # user = User.objects.get(username=username)
        if user.is_active is True:
            user.is_active = False
            user.save()
            return JsonResponse({
                "status": 0,
                "message": "封禁成功"
            })
        else:
            user.is_active = True
            user.save()
            return JsonResponse({
                "status": 0,
                "message": "解禁成功"
            })


class Profiles:
    @staticmethod
    def change_profiles(request):
        if request.method == 'POST':
            data = json.loads(request.body)
            id = data.get("id")
            user = UserInfo.objects.get(id=id)
            user.userName = data.get('username')
            user.email = data.get('email')
            user.phone = data.get('phone')
            user.age = data.get('age')
            user.preferredType = data.get('ptype')
            user.intro = data.get('intro')
            user.permission = data.get('permission')
            user.save()
            return JsonResponse({
                "status": 0,
                "message": "修改成功"
            })
        else:
            print(2)
            return JsonResponse({
                "status": 1,
                "message": "请求方式错误"
            })

    @staticmethod
    def get_profile(request):
        if request.method == 'POST':
            data = json.loads(request.body)
            user_id = data.get("id")
            if user_id is None and request.user.is_authenticated:
                user_id = request.user.id
            if User.objects.filter(id=user_id).first() is None:
                return JsonResponse({
                    "status": 3,
                    "message": "id not exist"
                })
            user = User.objects.get(id=user_id)
            # print(user_id)
            # userprofile = Profile.objects.get(user_id = user_id)
            if UserInfo.objects.filter(user_id=user_id).exists():
                userinfo = UserInfo.objects.get(user_id=user_id)
            else:
                return JsonResponse({
                    "status": 3,
                    "message": "profile not exist"
                })
            # userprofile = Profile.objects.create(user_id = user_id)
            # if userprofile.avatar and hasattr(userprofile.avatar, 'url'):
            #     avatar = prefix + str(userprofile.avatar.url)
            # else:
            #     avatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
            # avatar = user.avatar
            username = user.username
            nickname = userinfo.nickname
            email = user.email
            phone = userinfo.phone
            age = userinfo.age
            level = userinfo.level
            preferred = userinfo.preferredType
            status = userinfo.status
            gender = userinfo.gender
            is_administrator = userinfo.isAdmin
            realname = userinfo.realname
            return JsonResponse({
                "status": 0,
                "data": {
                    "username": username,
                    "email": email,
                    "phone": phone,
                    # "avatar": avatar,
                    "userid": user_id,
                    "nickname": nickname,
                    "age": age,
                    "level": level,
                    "preferred": preferred,
                    "status": status,
                    "gender": gender,
                    "is_admin": is_administrator,
                    "realname": realname
                }
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用post请求"
            })

# # 获取验证码
# # 获取验证码图片的视图
#
# def get_valid_img(request):
#     # 获取随机颜色的函数
#     def get_random_color():
#         return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
#
#     # 生成一个图片对象
#     img_obj = Image.new(
#         'RGB',
#         (220, 35),
#         get_random_color()
#     )
#     # 在生成的图片上写字符
#     font = ImageFont.truetype('arial.ttf', 30)
#     # 生成一个图片画笔对象
#     draw_obj = ImageDraw.Draw(img_obj)
#     # 开始生成随机字符串并且写到图片上
#     tmp_list = []
#     for i in range(4):
#         u = chr(random.randint(65, 90))  # 生成大写字母
#         l = chr(random.randint(97, 122))  # 生成小写字母
#         n = str(random.randint(0, 9))  # 生成数字，注意要转换成字符串类型
#
#         tmp = random.choice([u, l, n])
#         tmp_list.append(tmp)
#         draw_obj.text((20 + 40 * i, 0), tmp, fill=get_random_color(), font=font)
#
#     print(tmp_list)
#     mystr = ""
#     for s in tmp_list:
#         mystr += s
#     # 加干扰线
#     width = 220  # 图片宽度（防止越界）
#     height = 35
#     for i in range(4):
#         x1 = random.randint(0, width)
#         x2 = random.randint(0, width)
#         y1 = random.randint(0, height)
#         y2 = random.randint(0, height)
#         draw_obj.line((x1, y1, x2, y2), fill=get_random_color())
#
#     # 加干扰点
#     for i in range(40):
#         draw_obj.point((random.randint(0, width), random.randint(0, height)), fill=get_random_color())
#         x = random.randint(0, width)
#         y = random.randint(0, height)
#         draw_obj.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())
#     with open(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/media/checkcode/{}.png'.format(mystr),
#               'wb') as f:
#         img_obj.save(f, format='png')
#     return JsonResponse({
#         "url": "http://182.92.239.145" + '/media/checkcode/{}.png'.format(mystr),
#         "code": mystr
#     })
